# WebRTC Project Startup Script
# Simple version without encoding issues

param(
    [ValidateSet("dev", "prod", "docker")]
    [string]$Mode = "dev",
    [switch]$Clean = $false,
    [switch]$WithServices = $false,
    [switch]$Verbose = $false,
    [switch]$Help = $false
)

function Write-Info($Message, $Color = "White") {
    Write-Host $Message -ForegroundColor $Color
}

function Show-Help {
    Write-Info "WebRTC Project Startup Script" "Blue"
    Write-Info ""
    Write-Info "Usage:" "Yellow"
    Write-Info "  .\scripts\start-webrtc.ps1 [options]"
    Write-Info ""
    Write-Info "Options:" "Yellow"
    Write-Info "  -Mode <mode>     Run mode: dev (default), prod, docker"
    Write-Info "  -Clean           Clean build cache"
    Write-Info "  -WithServices    Start external services (RabbitMQ, Consul)"
    Write-Info "  -Verbose         Show detailed logs"
    Write-Info "  -Help            Show this help"
    Write-Info ""
    Write-Info "Examples:" "Yellow"
    Write-Info "  .\scripts\start-webrtc.ps1 -Mode dev -WithServices"
    Write-Info "  .\scripts\start-webrtc.ps1 -Mode prod -Clean"
    Write-Info "  .\scripts\start-webrtc.ps1 -Mode docker"
}

function Test-Environment {
    Write-Info "[CHECK] Testing environment..." "Blue"
    
    # Check .NET SDK
    try {
        $dotnetVersion = dotnet --version 2>$null
        if ($dotnetVersion) {
            Write-Info "[OK] .NET SDK: $dotnetVersion" "Green"
        } else {
            throw ".NET SDK not found"
        }
    } catch {
        Write-Info "[ERROR] .NET SDK required. Download from https://dotnet.microsoft.com" "Red"
        exit 1
    }
    
    # Check Docker if needed
    if ($Mode -eq "docker" -or $WithServices) {
        try {
            $dockerVersion = docker --version 2>$null
            if ($dockerVersion) {
                Write-Info "[OK] Docker: $dockerVersion" "Green"
            } else {
                throw "Docker not found"
            }
        } catch {
            Write-Info "[ERROR] Docker required for this mode" "Red"
            exit 1
        }
    }
}

function Clean-Build {
    if ($Clean) {
        Write-Info "[CLEAN] Cleaning build cache..." "Blue"
        $folders = @("bin", "obj", "publish")
        foreach ($folder in $folders) {
            if (Test-Path $folder) {
                Remove-Item -Recurse -Force $folder
                Write-Info "[CLEAN] Removed $folder" "Yellow"
            }
        }
        Write-Info "[OK] Build cache cleaned" "Green"
    }
}

function Start-Services {
    if ($WithServices) {
        Write-Info "[SERVICES] Checking external services..." "Blue"
        Write-Info "[INFO] Using external RabbitMQ server: 192.168.10.254:5672" "Cyan"
        Write-Info "[INFO] Using external Consul server: 192.168.10.254:8500" "Cyan"
        Write-Info "[OK] External services configured" "Green"
        
        # 可选：测试外部服务连接
        Write-Info "[TEST] Testing external service connectivity..." "Blue"
        try {
            # 测试 Consul 连接
            $consulResponse = Invoke-WebRequest -Uri "http://192.168.10.254:8500/v1/status/leader" -TimeoutSec 5 -UseBasicParsing
            if ($consulResponse.StatusCode -eq 200) {
                Write-Info "[OK] Consul server is reachable" "Green"
            }
        } catch {
            Write-Info "[WARN] Consul server connection test failed: $($_.Exception.Message)" "Yellow"
        }
    }
}

function Start-Application {
    Write-Info "[START] Starting application in $Mode mode..." "Blue"
    
    switch ($Mode) {
        "dev" {
            $env:ASPNETCORE_ENVIRONMENT = "Development"
            $env:ASPNETCORE_URLS = "https://localhost:5001;http://localhost:5000"
            Write-Info "[INFO] Starting development server..." "Cyan"
            Write-Info "[INFO] URL: https://localhost:5001" "Cyan"
            if ($Verbose) { dotnet run --verbosity detailed } else { dotnet run }
        }
        "prod" {
            Write-Info "[BUILD] Building release version..." "Blue"
            dotnet publish -c Release -o ./publish
            if ($LASTEXITCODE -eq 0) {
                $env:ASPNETCORE_ENVIRONMENT = "Production"
                $env:ASPNETCORE_URLS = "https://localhost:5001;http://localhost:5000"
                Write-Info "[START] Starting production server..." "Cyan"
                dotnet ./publish/WebRtcProject.dll
            } else {
                Write-Info "[ERROR] Build failed" "Red"
                exit 1
            }
        }
        "docker" {
            Write-Info "[DOCKER] Building image..." "Blue"
            docker build -t webrtc-app .
            if ($LASTEXITCODE -eq 0) {
                docker stop webrtc-app 2>$null
                docker rm webrtc-app 2>$null
                docker run -d --name webrtc-app -p 5000:5000 -p 5001:5001 webrtc-app
                if ($LASTEXITCODE -eq 0) {
                    Write-Info "[OK] Docker container started" "Green"
                    Write-Info "[INFO] URL: https://localhost:5001" "Cyan"
                } else {
                    Write-Info "[ERROR] Container start failed" "Red"
                    exit 1
                }
            } else {
                Write-Info "[ERROR] Docker build failed" "Red"
                exit 1
            }
        }
    }
}

# Main execution
if ($Help) {
    Show-Help
    exit 0
}

Write-Info "================================================" "Cyan"
Write-Info "   WebRTC Video Call System" "Cyan"
Write-Info "================================================" "Cyan"
Write-Info "Mode: $Mode | Clean: $Clean | Services: $WithServices" "Yellow"
Write-Info "================================================" "Cyan"

try {
    Test-Environment
    Clean-Build
    Start-Services
    Start-Application
} catch {
    Write-Info "[ERROR] Startup failed: $($_.Exception.Message)" "Red"
    exit 1
} 